<template>
  <div class="video-player-container">
    <el-card class="video-card" shadow="never">
      <template #header>
        <div class="video-header">
          <span class="video-title">视频播放器</span>
          <div class="video-controls">
            <el-button-group>
              <el-button 
                :type="isPlaying ? 'primary' : 'default'" 
                @click="togglePlay"
                :icon="isPlaying ? 'VideoPause' : 'VideoPlay'"
              >
                {{ isPlaying ? '暂停' : '播放' }}
              </el-button>
              <el-button @click="toggleMute" :icon="isMuted ? 'MuteNotification' : 'Microphone'">
                {{ isMuted ? '取消静音' : '静音' }}
              </el-button>
              <el-button @click="toggleFullscreen" icon="FullScreen">
                {{ isFullscreen ? '退出全屏' : '全屏' }}
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>
      
      <div class="video-wrapper">
        <video 
          ref="videoEl"
          class="el-video-player"
          :src="videoSource"
          controls
          playsinline
          @play="onPlay"
          @pause="onPause"
          @volumechange="onVolumeChange"
          @loadedmetadata="onLoadedMetadata"
        >
          <track 
            v-for="(subtitle, index) in subtitles" 
            :key="index"
            kind="subtitles"
            :src="subtitle.url"
            :srclang="subtitle.lang || 'en'"
            :label="subtitle.label"
            :default="index === 0"
          >
          您的浏览器不支持视频播放。
        </video>
      </div>
      
      <div class="player-controls">
        <div class="control-group">
          <span class="control-label">播放速度：</span>
          <el-select v-model="playbackRate" @change="applyPlaybackRate" size="small">
            <el-option v-for="rate in playbackRates" :key="rate" :label="`${rate}x`" :value="rate" />
          </el-select>
        </div>
        
        <div class="control-group">
          <span class="control-label">音量：</span>
          <el-slider 
            v-model="volume" 
            :min="0" 
            :max="1" 
            :step="0.1"
            :show-tooltip="false"
            @input="setVolume"
            style="width: 100px;"
          />
          <span class="volume-text">{{ Math.round(volume * 100) }}%</span>
        </div>
        
        <div class="control-group">
          <el-button @click="togglePictureInPicture" type="text" size="small">
            <el-icon><FullScreen /></el-icon>
            画中画
          </el-button>
        </div>
      </div>
      
      <div class="video-info">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="当前时间">{{ currentTimeText }}</el-descriptions-item>
          <el-descriptions-item label="总时长">{{ durationText }}</el-descriptions-item>
          <el-descriptions-item label="视频格式">{{ videoType }}</el-descriptions-item>
          <el-descriptions-item label="分辨率">{{ resolution }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElCard, ElButton, ElButtonGroup, ElSelect, ElOption, ElSlider, ElDescriptions, ElDescriptionsItem, ElIcon } from 'element-plus';
import { VideoPlay, VideoPause, Microphone, MuteNotification, FullScreen } from '@element-plus/icons-vue';

const props = defineProps({
  source: { type: Object, required: true },
  subtitles: { type: Array, default: () => [] }
});

const videoEl = ref(null);
const isPlaying = ref(false);
const isMuted = ref(false);
const isFullscreen = ref(false);
const volume = ref(0.7);
const playbackRate = ref(1.0);
const currentTime = ref(0);
const duration = ref(0);
const videoWidth = ref(0);
const videoHeight = ref(0);

const playbackRates = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];

const videoSource = computed(() => props.source?.url || '');
const videoType = computed(() => {
  const url = videoSource.value;
  if (url.includes('.m3u8')) return 'HLS';
  if (url.includes('.mp4')) return 'MP4';
  return '未知';
});
const resolution = computed(() => {
  if (videoWidth.value && videoHeight.value) {
    return `${videoWidth.value}x${videoHeight.value}`;
  }
  return '未知';
});
const currentTimeText = computed(() => formatTime(currentTime.value));
const durationText = computed(() => formatTime(duration.value));

const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

const togglePlay = () => {
  const video = videoEl.value;
  if (!video) return;
  
  if (video.paused) {
    video.play();
  } else {
    video.pause();
  }
};

const toggleMute = () => {
  const video = videoEl.value;
  if (!video) return;
  
  video.muted = !video.muted;
  isMuted.value = video.muted;
};

const setVolume = (value) => {
  const video = videoEl.value;
  if (!video) return;
  
  video.volume = value;
  isMuted.value = value === 0;
};

const applyPlaybackRate = () => {
  const video = videoEl.value;
  if (!video) return;
  
  video.playbackRate = playbackRate.value;
};

const toggleFullscreen = () => {
  const video = videoEl.value;
  if (!video) return;
  
  if (!document.fullscreenElement) {
    video.requestFullscreen?.().catch(err => {
      console.warn('全屏请求失败:', err);
    });
  } else {
    document.exitFullscreen?.();
  }
};

const togglePictureInPicture = async () => {
  const video = videoEl.value;
  if (!video) return;
  
  try {
    if (document.pictureInPictureElement) {
      await document.exitPictureInPicture();
    } else if (video.requestPictureInPicture) {
      await video.requestPictureInPicture();
    }
  } catch (error) {
    ElMessage.warning('画中画功能不可用');
  }
};

const onPlay = () => {
  isPlaying.value = true;
};

const onPause = () => {
  isPlaying.value = false;
};

const onVolumeChange = () => {
  const video = videoEl.value;
  if (!video) return;
  
  volume.value = video.volume;
  isMuted.value = video.muted;
};

const onLoadedMetadata = () => {
  const video = videoEl.value;
  if (!video) return;
  
  duration.value = video.duration;
  videoWidth.value = video.videoWidth;
  videoHeight.value = video.videoHeight;
};

const updateCurrentTime = () => {
  const video = videoEl.value;
  if (!video) return;
  
  currentTime.value = video.currentTime;
};

// 键盘快捷键
const handleKeydown = (event) => {
  const video = videoEl.value;
  if (!video) return;
  
  switch (event.code) {
    case 'Space':
      event.preventDefault();
      togglePlay();
      break;
    case 'ArrowLeft':
      event.preventDefault();
      video.currentTime = Math.max(0, video.currentTime - 5);
      break;
    case 'ArrowRight':
      event.preventDefault();
      video.currentTime = Math.min(video.duration, video.currentTime + 5);
      break;
    case 'ArrowUp':
      event.preventDefault();
      volume.value = Math.min(1, volume.value + 0.1);
      setVolume(volume.value);
      break;
    case 'ArrowDown':
      event.preventDefault();
      volume.value = Math.max(0, volume.value - 0.1);
      setVolume(volume.value);
      break;
    case 'KeyM':
      event.preventDefault();
      toggleMute();
      break;
    case 'KeyF':
      event.preventDefault();
      toggleFullscreen();
      break;
  }
};

// 监听视频源变化
watch(() => props.source, (newSource) => {
  if (newSource?.url) {
    // 给视频加载一点时间
    setTimeout(() => {
      const video = videoEl.value;
      if (video) {
        video.load();
      }
    }, 100);
  }
}, { immediate: true });

onMounted(() => {
  window.addEventListener('keydown', handleKeydown);
  
  // 监听时间更新
  const video = videoEl.value;
  if (video) {
    video.addEventListener('timeupdate', updateCurrentTime);
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown);
  
  const video = videoEl.value;
  if (video) {
    video.removeEventListener('timeupdate', updateCurrentTime);
  }
});
</script>

<style scoped>
.video-player-container {
  width: 100%;
}

.video-card {
  background: #1a202c;
  border: 1px solid #2d3748;
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.video-title {
  font-size: 16px;
  font-weight: 600;
  color: #e2e8f0;
}

.video-wrapper {
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.el-video-player {
  width: 100%;
  height: 56vh;
  max-height: 600px;
  background: #000;
}

.player-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 16px 0;
  border-top: 1px solid #2d3748;
  margin-top: 16px;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.control-label {
  font-size: 14px;
  color: #a0aec0;
  white-space: nowrap;
}

.volume-text {
  font-size: 12px;
  color: #718096;
  min-width: 40px;
}

.video-info {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #2d3748;
}

:deep(.el-descriptions__label) {
  color: #a0aec0 !important;
}

:deep(.el-descriptions__content) {
  color: #e2e8f0 !important;
}
</style>